﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Eagles.Application.Model;
using Eagles.Application.Model.Common;
using Eagles.Application.Model.Enums;
using Eagles.Application.Model.News.Model;
using Eagles.Application.Model.News.Requset;
using Eagles.Application.Model.News.Response;
using Eagles.Application.Model.PartyMember.Model;
using Eagles.Base;
using Eagles.Base.Cache;
using Eagles.Base.Json.Implement;
using Eagles.Base.Utility;
using Eagles.DomainService.Model.App;
using Eagles.DomainService.Model.News;
using Eagles.DomainService.Model.User;
using Eagles.Interface.Core;
using Eagles.Interface.DataAccess;

namespace Eagles.DomainService.Core
{
    public class NewsHandler : INewsHandler
    {
        private readonly INewsDataAccess dataAccess;
        private readonly IBranchDataAccess BranchdataAccess;
        private readonly IColumnDataAccess ColumndataAccess;
        private readonly ICacheHelper cacheHelper;
        private readonly IOperGroupHandler OperGroupdataAccess;

        public NewsHandler(INewsDataAccess dataAccess, ICacheHelper cacheHelper, IColumnDataAccess columndataAccess, IBranchDataAccess branchdataAccess, IOperGroupHandler operGroupdataAccess)
        {
            this.dataAccess = dataAccess;
            this.cacheHelper = cacheHelper;
            ColumndataAccess = columndataAccess;
            BranchdataAccess = branchdataAccess;
            OperGroupdataAccess = operGroupdataAccess;
        }

        public bool EditNews(EditNewRequset requset)
        {



            var authority = OperGroupdataAccess.GetAuthorityByToken(new RequestBase() { Token = requset.Token });
            if (authority.List.Exists(x => x.FunCode == "Audit001"))
            {
                requset.Info.Status = "0";
            }
            else
            {
                requset.Info.Status = "-1";
            }


            TbNews mod;
            var token = cacheHelper.GetData<TbUserToken>(requset.Token);
            var now = DateTime.Now;
            if (requset.Info.NewsId > 0)
            {
                mod = new TbNews
                {
                    Attach1 = requset.Info.Attach1,
                    Attach2 = requset.Info.Attach2,
                    Attach3 = requset.Info.Attach3,
                    Attach4 = requset.Info.Attach4,
                    AttachName1 = requset.Info.AttachName1,
                    AttachName2 = requset.Info.AttachName2,
                    AttachName3 = requset.Info.AttachName3,
                    AttachName4 = requset.Info.AttachName4,
                    Author = requset.Info.Author,
                    BeginTime = requset.Info.StarTime,
                    EndTime = requset.Info.EndTime,
                    HtmlContent = requset.Info.Content,
                    //  CreateTime = requset.Info.CreateTime.ConvertToDateTime(),
                    Module = requset.Info.ModuleId,
                    NewsId = requset.Info.NewsId,
                    ImageUrl = requset.Info.NewsImg,
                    Title = requset.Info.NewsName,
                    NewsType = requset.Info.NewsType,
                    Source = requset.Info.Source,
                    TestId = requset.Info.TestId,
                    OrgId = token.OrgId,
                    CanStudy = requset.Info.CanStudy,
                    ExternalUrl = requset.Info.ExternalUrl,
                    IsAttach = requset.Info.IsAttach,
                    IsClass = requset.Info.IsClass,
                    IsExternal = requset.Info.IsExternal,
                    IsImage = requset.Info.IsImage,
                    IsLearning = requset.Info.IsLearning,
                    IsText = requset.Info.IsLearning,
                    IsVideo = requset.Info.IsVideo,
                    OperId = token.UserId,
                    ShortDesc = requset.Info.ShortDesc,
                    RewardsScore=requset.Info.RewardsScore,
                    StudyTime=requset.Info.StudyTime,
                    Status=requset.Info.Status,
                    IsTop = requset.Info.IsTop
                };

                return dataAccess.EditNews(mod) > 0;

            }
            else
            {
                mod = new TbNews
                {
                    Attach1 = requset.Info.Attach1,
                    Attach2 = requset.Info.Attach2,
                    Attach3 = requset.Info.Attach3,
                    Attach4 = requset.Info.Attach4,
                    AttachName1 = requset.Info.AttachName1,
                    AttachName2 = requset.Info.AttachName2,
                    AttachName3 = requset.Info.AttachName3,
                    AttachName4 = requset.Info.AttachName4,
                    Author = requset.Info.Author,
                    BeginTime = requset.Info.StarTime,
                    EndTime = requset.Info.EndTime,
                    HtmlContent = requset.Info.Content,
                    CreateTime = now,
                    Module = requset.Info.ModuleId,
                    NewsId = requset.Info.NewsId,
                    ImageUrl = requset.Info.NewsImg,
                    Title = requset.Info.NewsName,
                    NewsType = requset.Info.NewsType,
                    Source = requset.Info.Source,
                    TestId = requset.Info.TestId,
                    OrgId = token.OrgId,
                    CanStudy = requset.Info.CanStudy,
                    ExternalUrl = requset.Info.ExternalUrl,
                    IsAttach = requset.Info.IsAttach,
                    IsClass = requset.Info.IsClass,
                    IsExternal = requset.Info.IsExternal,
                    IsImage = requset.Info.IsImage,
                    IsLearning = requset.Info.IsLearning,
                    IsText = requset.Info.IsLearning,
                    IsVideo = requset.Info.IsVideo,
                    OperId = token.UserId,
                    ShortDesc = requset.Info.ShortDesc,
                    Status = requset.Info.Status,
                    RewardsScore = requset.Info.RewardsScore,
                    StudyTime = requset.Info.StudyTime,
                    IsTop = requset.Info.IsTop,
                    BranchId = token.BranchId
                };

                return dataAccess.CreateNews(mod) > 0;

            }
        }

        public bool RemoveNews(RemoveNewRequset requset)
        {

            return dataAccess.RemoveNews(requset) > 0;

        }

        public GetNewDetailResponse GetNewsDetail(GetNewDetailRequset requset)
        {
            var response = new GetNewDetailResponse();
            var detail = dataAccess.GetNewsDetail(requset);
            var attach = new List<Attachment>()
            {
                new Attachment()
                {
                    AttachmentUrl = detail.Attach1,
                    AttachmentName = detail.AttachName1
                },
                new Attachment()
                {
                    AttachmentUrl = detail.Attach2,
                    AttachmentName = detail.AttachName2
                },
                new Attachment()
                {
                    AttachmentUrl = detail.Attach3,
                    AttachmentName = detail.AttachName3
                },new Attachment()
                {
                    AttachmentUrl = detail.Attach4,
                    AttachmentName = detail.AttachName4
                }
            };
            response.Info = new QueryNewsDetail()
            {
                //AuditStatus = AuditStatus.审核通过,
                AuditStatus = AuditStatus.审核通过,
                Author = detail.Author,
                CreateTime = detail.CreateTime.FormartDatetime(),
                NewsId = detail.NewsId,
                NewsImg = detail.ImageUrl,
                NewsName = detail.Title,
                NewsType = detail.NewsType,
                Source = detail.Source,
                StarTime = detail.CreateTime,
                EndTime = detail.EndTime,
                ModuleId = detail.Module,
                TestId = detail.TestId,
                Content = detail.HtmlContent,
                //OrgId = detail.OrgId,
                ExternalUrl = detail.ExternalUrl,
                BeginTime=detail.BeginTime,
                Attachments = attach,
                IsAttach = detail.IsAttach,
                IsClass = detail.IsClass,
                IsExternal = detail.IsExternal,
                IsImage = detail.IsImage,
                IsLearning = detail.IsLearning,
                IsText = detail.IsLearning,
                IsVideo = detail.IsVideo,
                RewardsScore = detail.RewardsScore,
                StudyTime = detail.StudyTime,
                CanStudy=detail.CanStudy,
                IsTop = detail.IsTop,
                TestName=detail.TestName
                //NewsType = detail.NewsType,
            };

            response.Info.Attachments = response.Info.Attachments
                .Where(x => !string.IsNullOrWhiteSpace(x.AttachmentName) || !string.IsNullOrWhiteSpace(x.AttachmentUrl)).ToList();

            return response;
        }

        public GetNewResponse GetNews(GetNewRequset requset)
        {

            var response = new GetNewResponse
            {
                TotalCount = 0
            };
            var list = dataAccess.GetNewsList(requset, out int totalCount) ?? new List<TbNews>();

            if (list.Count == 0) throw new TransactionException("M01");

          
            response.TotalCount = totalCount;
            response.List = list.Select(x => new New
            {
                //AuditStatus = AuditStatus.审核通过,
                Author = x.Author,
                CreateTime = x.CreateTime.FormartDatetime(),
                NewsId = x.NewsId,
                NewsImg = x.ImageUrl,
                NewsName = x.Title,
                NewsType = x.NewsType,
                Source = x.Source,
                Status = x.Status,
                ModuleName = x.ModuleName,
                //OrgId = x.OrgId,
                IsTop = x.IsTop,
                BranchId = x.BranchId,
                BranchName = x.BranchName,
                IsPublicOrg = x.IsPublicOrg
            }).ToList();
            return response;
        }

        public ImportNewResponse ImportNews(ImportNewRequset requset)
        {
            var now = DateTime.Now;



            var response = new ImportNewResponse { NewList = new List<ExternalNew>() };
            Regex regex = new Regex("^1[123456789]\\d{9}$");
            
            var news=new List<TbNews>();

            var token = cacheHelper.GetData<TbUserToken>(requset.Token);

            var columnIdList = requset.Info.Select(x => x.ColumnId).ToList();

            if (columnIdList.Count == 0)
            {
              throw new TransactionException("M10");
            }

            List<TbAppModule>  module = ColumndataAccess.GetColumnByName(columnIdList);

           


            foreach (ExternalNew md in requset.Info)
            {

                if (string.IsNullOrEmpty(md.ExternalUrl))
                {
                  
                    md.ErrorReason = "外部链接为空！";
                    response.NewList.Add(md);
                    continue;
                }

                if (string.IsNullOrEmpty(md.NewsImg))
                {

                    md.ErrorReason = "新闻图片为空！";
                    response.NewList.Add(md);
                    continue;
                }
                if (string.IsNullOrEmpty(md.NewsName))
                {

                    md.ErrorReason = "新闻名字为空！";
                    response.NewList.Add(md);
                    continue;
                }

                if (string.IsNullOrEmpty(md.Source))
                {

                    md.ErrorReason = "新闻来源为空！";
                    response.NewList.Add(md);
                    continue;
                }

                var moduleInfo = module.FirstOrDefault(x => x.ModuleId == md.ColumnId);
                if (moduleInfo == null)
                {
                    md.ErrorReason = "栏目不存在！";
                    response.NewList.Add(md);
                    continue;
                }


                news.Add(new TbNews
                {
                    BranchId=token.BranchId,
                    OrgId=token.OrgId,
                    OperId=token.UserId,
                    Status="-1",
                    ImageUrl = md.NewsImg,
                    Title = md.NewsName,
                    ExternalUrl = md.ExternalUrl,
                    IsExternal = 1,
                    CreateTime = now,
                    Source = md.Source,
                    Module= moduleInfo.ModuleId
                });


            }

            if (news.Count == 0)
            {
                response.ImportStart = 0;
                return response;
            }




            if (dataAccess.ImportNews(news) <= 0)
            {
                response.NewList.AddRange(news.Select(x => new ExternalNew()
                {
                    NewsImg = x.ImageUrl,
                    NewsName = x.Title,
                    ExternalUrl = x.ExternalUrl,
                    Source = x.Source,
                    ErrorReason = "添加数据异常"
                }));
            }



            response.ImportStart = 1;

            if (response.NewList.Count > 0)
            {
                response.ImportStart = 2;
            }

            return response;

           
        }

        public bool SetNewsPublicOrg(SetNewsPublicOrgRequset requset)
        {
            return dataAccess.SetNewsPublicOrg(requset) > 0;
        }
    }
}
